import java.util.*;

//孩子表示法
public class BinaryTree {

    //节点，内部类
    static class TreeNode {
        public char val;//数据域
        public TreeNode left; //左孩子的引用，常常代表左孩子为根的整颗左子树
        public TreeNode right; //右孩子的引用，常常代表右孩子为根的整颗右子树

        public TreeNode(char val) {
            this.val = val;
        }
    }
    //public TreeNode root; //二叉树的根节点

    /**
     * 创建一颗二叉树(穷举的方式) 创建成功后 返回根节点
     *
     * @return
     */
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }


    //前序遍历 根 -> 左子树 -> 右子树 递归
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }


    //把 前序遍历的结果 存储到List 当中
    //利用子问题思路，实现有返回值的前序遍历
    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        ret.add(root.val);
        //利用每次回溯的返回值
        List<Character> leftTree = preorderTraversal(root.left);
        //每次回溯保证递归结果(数组)被添加到前一次递归结果(数组)的后面
        ret.addAll(leftTree);
        List<Character> rightTree = preorderTraversal(root.right);
        ret.addAll(rightTree);

        return ret;
    }



    /*List<Character> ret = new ArrayList<>();//就目前代码而言，这段代码不能放在里面，
    //因为每次递归都创建一个新的数组，且回溯返回的值并没有接收

    //把 前序遍历的结果 存储到List 当中
    public List<Character> preorderTraversal(TreeNode root) {
        if (root == null) {
            return ret;
        }
        ret.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);

        return ret;
    }*/

    //先序非递归遍历实现
    public void preOrderNor(TreeNode root) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;//cur往左走
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }


    //中序遍历 左 -> 根 -> 右
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }

        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }


    //中序遍历
    //利用子问题思路，实现有返回值的中序遍历
    public List<Character> inOrderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }

        //利用每次回溯的返回值
        List<Character> leftTree = inOrderTraversal(root.left);
        //每次回溯保证递归结果(数组)被添加到前一次递归结果(数组)的后面
        ret.addAll(leftTree);
        ret.add(root.val);//根节点
        List<Character> rightTree = inOrderTraversal(root.right);
        ret.addAll(rightTree);

        return ret;
    }

    //中序遍历非递归实现
    public void inOrderNor(TreeNode root) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }

    }


    //后序遍历 左 -> 右 -> 根
    public void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }

        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

    //后序遍历
    //利用子问题思路，实现有返回值的后序遍历
    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }

        //利用每次回溯的返回值
        List<Character> leftTree = postorderTraversal(root.left);
        //每次回溯保证递归结果(数组)被添加到前一次递归结果(数组)的后面
        ret.addAll(leftTree);
        List<Character> rightTree = postorderTraversal(root.right);
        ret.addAll(rightTree);

        ret.add(root.val);//根节点

        return ret;
    }


    public int nodeSize;

    //遍历思路
    // 获取树中节点的个数
    public int size1(TreeNode root) {
        //判断该二叉树是否为空树，同时也是递归结束条件
        if (root == null) {
            return 0;
        }
        nodeSize++;
        size1(root.left);
        size1(root.right);
        return nodeSize;
    }

    //子问题思路
    //获取树中节点的个数
    public int size(TreeNode root) {
        //判断该二叉树是否为空树，同时也是递归结束条件
        if (root == null) {
            return 0;
        }
        return size(root.left) + size(root.right) + 1;
    }


    public int leafSize;

    //遍历思路
    // 获取叶子节点的个数
    public int getLeafNodeCount1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
        return leafSize;
    }


    //子问题思路
    //获取叶子节点的个数
    public int getLeafNodeCount(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount(root.left)
                + getLeafNodeCount(root.right);
    }


    // 获取第K层节点的个数
    public int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1)
                + getKLevelNodeCount(root.right, k - 1);
    }


    // 获取二叉树的高度
    public int getHeight(TreeNode root) {
        //判断该二叉树是否为空树，同时也是递归结束条件
        if (root == null) {
            return 0;
        }

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return (leftHeight > rightHeight) ? (leftHeight + 1) : (rightHeight + 1);

        //本身没问题，但是如果在0J上跑，可能出现超出时间限制
        //因为遍历了两次，重复计算了左右子树
        /*return getHeight(root.left) > getHeight(root.right)
                ? getHeight(root.left) + 1 : getHeight(root.right) + 1;*/
    }


    // 检测值为value的元素是否存在
    public TreeNode find(TreeNode root, char val) {
        if (root == null) {
            return root;
        }
        if (root.val == val) {
            return root;
        }
        TreeNode ret1 = find(root.left, val);
        if (ret1 != null) {
            return ret1;//不去右边
        }

        TreeNode ret2 = find(root.right, val);
        if (ret2 != null) {
            return ret2;
        }
        return null;
    }



   /* //检查两颗树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //只要存在结构上的不同直接返回false
        if(p == null && q!= null || p!=null && q == null) {
            return false;
        }
        //上述代码代码走完之后 要么是两个都为空，要么是两个都不为空
        if(p == null && q == null) {
            return true;
        }
        //代码走到这里  两个都不为空,判断值是否一样
        if(p.val != q.val) {
            return false;
        }
        //p != null && q!=null  &&  p.val == q.val;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }*/


    //另一棵树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null || subRoot == null) {
            return false;
        }
        //1.是不是和根节点相同
        if (isSameTree(root, subRoot)) {
            return true;
        }
        //判断是不是root的左子树
        if (isSubtree(root.left, subRoot)) {
            return true;
        }
        //判断是不是root的右子树
        if (isSubtree(root.right, subRoot)) {
            return true;
        }
        //返回
        return false;
    }

    //检查两个树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q != null || p != null && q == null) {
            return false;
        }
        //走到这里，p和q 要么都为空 ，要么都不为空
        if (p == null && q == null) {
            return true;
        }
        //走到这里，p和q 一定都不为空了，比较他们的val值
        if (p.val != q.val) {
            return false;
        }
        //走到这里，p和q都不为空 且val值一样
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }


    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        //空树不翻转直接返回
        if (root == null) {
            return root;
        }
        //这行代码是走到叶子节点，不用交换空的节点了
        if (root.left == null && root.right == null) {
            return root;
        }
        //交换
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }


    //判断一颗二叉树是否是平衡二叉树
    //最坏情况下 每个节点 都要求高度
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        //先求当前root，左树和右树的高度
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);

        return Math.abs(leftHeight - rightHeight) <= 1
                && isBalanced(root.left) && isBalanced(root.right);
    }

    //计算二叉树最大深度
    public int maxDepth(TreeNode root) {
        //判断该二叉树是否为空树，同时也是递归结束条件
        if (root == null) {
            return 0;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }


    //对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;

        return isSymmetricChild(root.left, root.right);
    }

    private boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        if ((leftTree == null && rightTree != null) || (leftTree != null && rightTree == null)) {
            return false;
        }
        if (leftTree == null && rightTree == null) {
            return true;
        }
        // root.left != null && root.right != null 判断值是否相同
        if (leftTree.val != rightTree.val) {
            return false;
        }
        return isSymmetricChild(leftTree.left, rightTree.right)
                && isSymmetricChild(leftTree.right, rightTree.left);
    }


    //二叉树的构建及遍历
    /*class TreeNode {
        public char val; //数值域
        public TreeNode left;//左子树引用
        public TreeNode right;//右子树引用
        public TreeNode(char val) {
            this.val = val;
        }
    }
    public class Main {
        public static int i = 0;
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            // 注意 hasNext 和 hasNextLine 的区别
            while (in.hasNextLine()) { // 注意 while 处理多个 case
                String str = in.nextLine();
                TreeNode root = createTree(str);
                inOrder(root);
            }
        }

        //创建二叉树并返回根节点
        public static TreeNode createTree(String str) {
            //1.遍历字符串str
        *//*for(int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
        }*//*

            TreeNode root = null;
            if(str.charAt(i) != '#') {
                //2.前序遍历创建二叉树
                root = new TreeNode(str.charAt(i));
                i++;
                root.left = createTree(str);
                root.right = createTree(str);
            } else {
                //跳过'#'
                i++;
            }
            //3.返回根节点
            return root;
        }

        //中序遍历
        public static void inOrder(TreeNode root) {
            if(root == null) {
                return;
            }
            inOrder(root.left);
            System.out.print(root.val + " ");
            inOrder(root.right);
        }
    }*/


    //层序遍历 不带返回值的
    public void levelOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    //层序遍历 带返回值的
    /*public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> tmp = new ArrayList<>();

            while (size != 0) {
                TreeNode cur = queue.poll();
                //  System.out.print(cur.val + " ");
                tmp.add(cur.val);
                size--;

                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }*/


    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (root.left == null && root.right == null) {
            return true;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;//结束这个循环
            }
        }

        //代码走到这里队列一定不为空，因为null同样入队了
        //需要判断队列当中 是否有非空元素
        while (!queue.isEmpty()) {
            //一个元素一个元素 出队列判断 是不是空
            if (queue.poll() != null) {
                return false;
            }
        }
        return true;
    }


    //二叉树的最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        TreeNode leftTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor(root.right, p, q);

        if (leftTree != null && rightTree != null) {
            return root;
        } else if (leftTree != null) {
            return leftTree;
        } else {
            return rightTree;
        }
    }

}
